package com.example.linearlayoutdemo.network.auth.repository;

import android.content.Context;

import com.example.linearlayoutdemo.network.auth.auth.ApiService;
import com.example.linearlayoutdemo.network.auth.model.LoginResponse;
import com.example.linearlayoutdemo.network.auth.model.RegisterResponse;
import com.example.linearlayoutdemo.network.auth.model.User;
import com.example.linearlayoutdemo.network.auth.utils.SharedPreferencesUtil;

/**
 * 认证仓库类，处理所有与认证相关的数据操作
 */
public class AuthRepository {
    private static volatile AuthRepository instance;
    private final ApiService apiService;
    private final SharedPreferencesUtil sharedPreferencesUtil;

    private AuthRepository(Context context) {
        apiService = ApiService.getInstance();
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(context);
    }

    public static AuthRepository getInstance(Context context) {
        if (instance == null) {
            synchronized (AuthRepository.class) {
                if (instance == null) {
                    instance = new AuthRepository(context);
                }
            }
        }
        return instance;
    }

    /**
     * 登录
     */
    public void login(User user, ApiService.ApiCallback<LoginResponse> callback) {
        apiService.login(user, callback);
    }

    /**
     * 注册
     */
    public void register(User user, ApiService.ApiCallback<RegisterResponse> callback) {
        apiService.register(user, callback);
    }

    /**
     * 自动登录
     */
    public void autoLogin(ApiService.ApiCallback<LoginResponse> callback) {
        User savedUser = sharedPreferencesUtil.getUser();
        if (savedUser != null && savedUser.getToken() != null) {
            apiService.autoLogin(savedUser.getToken(), callback);
        } else {
            callback.onFailure(new Exception("没有保存的登录信息"));
            callback.onComplete();
        }
    }

    /**
     * 保存用户信息
     */
    public void saveUser(User user, boolean isAutoLogin) {
        sharedPreferencesUtil.saveUser(user);
        sharedPreferencesUtil.setAutoLogin(isAutoLogin);
    }

    /**
     * 检查是否可以自动登录
     */
    public boolean canAutoLogin() {
        return sharedPreferencesUtil.isAutoLogin() && sharedPreferencesUtil.hasLoginInfo();
    }

    /**
     * 退出登录
     */
    public void logout() {
        sharedPreferencesUtil.clearLoginInfo();
    }

    /**
     * 获取当前登录用户
     */
    public User getCurrentUser() {
        return sharedPreferencesUtil.getUser();
    }
}

